<template>
  <el-form :model="adminForm" status-icon :rules="rules" ref="formRef" label-width="100px" class="admin_form">
    <el-form-item label="管理员名称" prop="adminname">
      <el-input type="text" v-model="adminForm.adminname"></el-input>
    </el-form-item>
    <el-form-item label="管理员密码" prop="password">
      <el-input type="password" v-model="adminForm.password"></el-input>
    </el-form-item>

    <el-form-item label="管理员角色" prop="role">
      <el-radio-group v-model="adminForm.role">
        <el-radio :label="1">普通管理员</el-radio>
        <el-radio :label="2">超级管理员</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="管理员权限" prop="checkedKeys">
      <!-- node-key	每个树节点用来作为唯一标识的属性，整棵树应该是唯一的	string -->
      <el-tree
        ref="treeRef"
        :data="menus"
        node-key="name"
        show-checkbox
        :props="{ label: 'name', children: 'children' }"
        @check-change="checkChange"
        :check-strictly="true"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, FormInstance, TreeInstance } from 'element-plus';
import { adminAddRequest } from "@/api/userApi";
import menuArr from "@/router/menu";

// 表单引用
const formRef = ref<FormInstance>();
const treeRef = ref<TreeInstance>();

// 表单数据
const adminForm = reactive({
  adminname: "",
  password: "",
  role: 1,
  checkedKeys: [],
});

// 定义验证规则
const rules = {
  adminname: [
    { required: true, message: "请输入管理员名称", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入password", trigger: "blur" },
  ],
};

// 菜单数据
const menus = ref(menuArr);

// 处理节点选中状态变化
const checkChange = (data: any, checked: boolean, indeterminate: boolean) => {
  console.log(data, checked, indeterminate);
  // 可以在这里处理节点选中状态变化的逻辑
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  const valid = await formRef.value.validate().catch(() => false);
  if (valid) {
    console.log(treeRef.value?.getCheckedKeys(false));

    try {
      const res = await adminAddRequest({
        ...adminForm,
        checkedKeys: treeRef.value?.getCheckedKeys(false) || [],
      });
      console.log(res);

      // 提交成功后的处理
      ElMessage({
        type: 'success',
        message: '添加管理员成功'
      });

      resetForm(); // 重置表单
      // 刷新当前列表
    } catch (error) {
      console.log(error);
      ElMessage({
        type: 'error',
        message: '添加管理员失败'
      });
    }
  } else {
    console.log("error submit!");
    return false;
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  if (treeRef.value) {
    treeRef.value.setCheckedKeys([]);
  }
};

// 生命周期钩子
onMounted(() => {
  console.log('组件已挂载');
});
</script>
<style lang="css" scoped></style>
